/** 单例模式；
 *
 * @param {*} className 类的名字
 * @returns 单例类的实例
 */
export default function singleton(className: any) {
  let ins: any;
  let parameters: any[];
  return new Proxy(className, {
    construct(target, args) {
      if (!ins) {
        ins = new className(target, ...args);
        parameters = args;
      }
      if (!isSame(parameters, args)) {
        throw new Error("Cannot create another instance!");
      }
      return ins;
    },
  });
}

/** 是否相同
 *
 * @param {*} previous
 * @param {*} current
 * @returns
 */
function isSame(previous: any[], current: any[]) {
  if (previous.length !== current.length) {
    return false;
  }
  for (let i = 0, len = previous.length; i < len; i++) {
    if (previous[i] !== current[i]) {
      return false;
    }
  }
  return true;
}
